{% extends theme_path('admin/base.html') %}

{% block title %}文章管理{% endblock %}

{% block content %}
<div class="p-6">
    <div class="bg-white rounded-lg shadow-sm">
        <div class="px-6 py-4 border-b">
            <div class="flex flex-col lg:flex-row justify-between items-stretch lg:items-center space-y-4 lg:space-y-0">
                <h2 class="text-xl font-bold">文章管理</h2>
                <div class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 w-full lg:w-auto">
                    <div class="flex items-center space-x-2">
                        <button onclick="toggleAllArticles()" 
                                class="px-3 py-1 text-sm border border-gray-200 rounded hover:bg-gray-50">
                            全选
                        </button>
                        <button onclick="batchDeleteArticles()" 
                                class="px-3 py-1 text-sm bg-red-100 text-red-700 rounded hover:bg-red-200"
                                id="batchDeleteBtn" disabled>
                            批量删除
                        </button>
                    </div>
                    <form method="get" class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 flex-1">
                        <select name="search_type" 
                               class="px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full sm:w-auto">
                            <option value="title" {% if search_type == 'title' %}selected{% endif %}>标题</option>
                            <option value="id" {% if search_type == 'id' %}selected{% endif %}>ID</option>
                            <option value="author" {% if search_type == 'author' %}selected{% endif %}>作者</option>
                            <option value="status" {% if search_type == 'status' %}selected{% endif %}>状态</option>
                        </select>
                        <div class="relative flex-1">
                            <input type="text" name="q" value="{{ search_query }}"
                                   placeholder="搜索文章..." 
                                   class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                </svg>
                            </div>
                        </div>
                        <button type="submit" 
                                class="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200">
                            搜索
                        </button>
                    </form>
                    <a href="{{ url_for('admin.edit_article') }}"
                       class="w-full sm:w-auto px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors duration-200 text-center">
                        新建文章
                    </a>
                </div>
            </div>
        </div>

        <!-- 移动端列表视图 -->
        <div class="block sm:hidden">
            {% for article in pagination.items %}
            <div class="p-4 border-b border-gray-200">
                <div class="flex items-center justify-between mb-2">
                    <div class="flex items-center space-x-2">
                        <input type="checkbox" name="article_ids" value="{{ article.id }}" 
                               class="article-checkbox rounded border-gray-300"
                               onchange="updateBatchDeleteButton()">
                        <span class="text-sm text-gray-500">#{{ article.id }}</span>
                    </div>
                    <span class="px-2 py-1 text-xs rounded-full
                        {% if article.status == 'public' %}
                            bg-green-50 text-green-700 border border-green-100
                        {% elif article.status == 'private' %}
                            bg-red-50 text-red-700 border border-red-100
                        {% elif article.status == 'password' %}
                            bg-yellow-50 text-yellow-700 border border-yellow-100
                        {% elif article.status == 'draft' %}
                            bg-gray-50 text-gray-600 border border-gray-200
                        {% else %}
                            bg-blue-50 text-blue-700 border border-blue-100
                        {% endif %}">
                        {{ {
                            'public': '公开',
                            'private': '私密',
                            'password': '密码保护',
                            'draft': '草稿',
                            'pending': '待审核',
                            'hidden': '隐藏'
                        }[article.status] }}
                    </span>
                </div>

                <h3 class="text-base font-medium text-gray-900 mb-2">{{ article.title }}</h3>

                <div class="space-y-2 text-sm text-gray-500 mb-3">
                    <div class="flex items-center justify-between">
                        <span>作者: {{ article.author.nickname or article.author.username }}</span>
                        <span>浏览: {{ article.view_count }}</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span>评论: {{ '允许' if article.allow_comment else '禁止' }}</span>
                        <span>{{ article.created_at.strftime('%Y-%m-%d %H:%M') }}</span>
                    </div>
                </div>

                <div class="flex justify-end space-x-3">
                    <a href="{{ ArticleUrlGenerator.generate(article.id, article.category_id, article.created_at) }}"
                       target="_blank"
                       class="text-sm text-blue-600">查看</a>
                    <a href="{{ url_for('admin.edit_article', id=article.id) }}"
                       class="text-sm text-blue-600">编辑</a>
                    <button onclick="deleteArticle({{ article.id }})"
                            class="text-sm text-red-600">删除</button>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- 桌面端表格视图 -->
        <div class="hidden sm:block overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="w-12 px-4 py-3">
                            <input type="checkbox" id="selectAll" class="rounded border-gray-300">
                        </th>
                        <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-16">ID</th>
                        <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文章信息</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-24">作者</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">浏览</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">评论</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发布时间</th>
                        <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最后编辑</th>
                        <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-24">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    {% for article in pagination.items %}
                    <tr class="hover:bg-gray-50">
                        <td class="px-4 py-4">
                            <input type="checkbox" name="article_ids" value="{{ article.id }}" 
                                   class="article-checkbox rounded border-gray-300"
                                   onchange="updateBatchDeleteButton()">
                        </td>
                        <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ article.id }}</td>
                        <td class="px-4 sm:px-6 py-4">
                            <div class="flex flex-col space-y-2">
                                <!-- 标题 -->
                                <div class="text-sm font-medium text-gray-900 line-clamp-2">
                                    <a href="{{ ArticleUrlGenerator.generate(article.id, article.category_id, article.created_at) }}" 
                                       class="hover:text-blue-600 transition-colors duration-200" target="_blank">
                                        {{ article.title }}
                                    </a>
                                </div>
                                
                                <!-- 分类和标签 -->
                                <div class="flex flex-wrap gap-1.5 max-w-full overflow-hidden">
                                    {% for category in article.categories %}
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100">
                                        {{ category.name }}
                                    </span>
                                    {% endfor %}
                                    {% for tag in article.tags %}
                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-50 text-gray-600 border border-gray-200">
                                        {{ tag.name }}
                                    </span>
                                    {% endfor %}
                                </div>
                                
                                <!-- 移动端显示的额外信息 -->
                                <div class="sm:hidden text-xs text-gray-500 space-y-1">
                                    <div class="grid grid-cols-2 gap-2">
                                        <span>作者：{{ article.author.username }}</span>
                                        <span>状态：{{ {'public': '公开', 'private': '私密', 'password': '密码保护', 'draft': '草稿', 'pending': '待审核', 'hidden': '隐藏'}[article.status] }}</span>
                                        <span>浏览：{{ article.view_count }}</span>
                                        <span>评论：{{ '允许' if article.allow_comment else '禁止' }}</span>
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ article.author.username }}
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 inline-flex text-xs leading-5 font-medium rounded-full
                                {% if article.status == 'public' %}
                                    bg-green-50 text-green-700 border border-green-100
                                {% elif article.status == 'private' %}
                                    bg-red-50 text-red-700 border border-red-100
                                {% elif article.status == 'password' %}
                                    bg-yellow-50 text-yellow-700 border border-yellow-100
                                {% elif article.status == 'draft' %}
                                    bg-gray-50 text-gray-600 border border-gray-200
                                {% elif article.status == 'pending' %}
                                    bg-orange-50 text-orange-700 border border-orange-100
                                {% else %}
                                    bg-blue-50 text-blue-700 border border-blue-100
                                {% endif %}">
                                {{ {
                                    'public': '公开',
                                    'private': '私密',
                                    'password': '密码保护',
                                    'draft': '草稿',
                                    'pending': '待审核',
                                    'hidden': '隐藏'
                                }[article.status] }}
                            </span>
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ article.view_count }}
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 inline-flex text-xs leading-5 font-medium rounded-full
                                {% if article.allow_comment %}
                                    bg-green-100 text-green-800 border border-green-200
                                {% else %}
                                    bg-red-100 text-red-800 border border-red-200
                                {% endif %}">
                                {{ '允许' if article.allow_comment else '禁止' }}
                            </span>
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ article.created_at.strftime('%Y-%m-%d %H:%M') }}
                        </td>
                        <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ article.updated_at.strftime('%Y-%m-%d %H:%M') }}
                        </td>
                        <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm">
                            <div class="flex items-center space-x-3">
                                <a href="{{ url_for('admin.edit_article', id=article.id) }}"
                                   class="text-blue-600 hover:text-blue-900 transition-colors duration-200">编辑</a>
                                <button onclick="deleteArticle({{ article.id }})" 
                                        class="text-red-600 hover:text-red-900 transition-colors duration-200">删除</button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        {% if pagination.pages > 1 %}
        <div class="px-6 py-4 mt-4 border-t">
            {% with endpoint='admin.articles', kwargs={'q': search_query, 'search_type': search_type} %}
            {% include 'components/pagination.html' %}
            {% endwith %}
        </div>
        {% endif %}
    </div>
</div>

<script>
function deleteArticle(articleId) {
    showAlert('确定要删除此文章吗？', 'warning', '确认删除', function() {
        fetch(`{{ admin_url }}/article/${articleId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        })
        .then(response => {
            if (response.ok) {
                showAlert('文章删除成功', 'success', '成功');
                setTimeout(() => location.reload(), 200);
            } else {
                response.text().then(text => {
                    showAlert(text, 'error', '错误');
                });
            }
        });
    });
}

// 切换全选
function toggleAllArticles() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.getElementsByClassName('article-checkbox');
    
    Array.from(checkboxes).forEach(checkbox => {
        checkbox.checked = !selectAll.checked;
    });
    
    selectAll.checked = !selectAll.checked;
    updateBatchDeleteButton();
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const checkboxes = document.getElementsByClassName('article-checkbox');
    const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    batchDeleteBtn.disabled = selectedCount === 0;
    batchDeleteBtn.textContent = `批量删除${selectedCount ? `(${selectedCount})` : ''}`;
}

// 批量删除文章
function batchDeleteArticles() {
    const checkboxes = document.getElementsByClassName('article-checkbox');
    const selectedIds = Array.from(checkboxes)
        .filter(cb => cb.checked)
        .map(cb => cb.value);
    
    if (!selectedIds.length) return;
    
    showAlert(
        `确定要删除选中的 ${selectedIds.length} 篇文章吗？此操作不可恢复！`, 
        'warning',
        '确认删除',
        function() {
            fetch('{{ admin_url }}/articles/batch-delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    article_ids: selectedIds
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error', '错误');
                } else {
                    showAlert('文章已删除', 'success', '成功');
                    setTimeout(() => location.reload(), 500);
                }
            })
            .catch(error => {
                showAlert('删除失败', 'error', '错误');
            });
        },
        true
    );
}

// 监听全选框变化
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.getElementsByClassName('article-checkbox');
    Array.from(checkboxes).forEach(checkbox => {
        checkbox.checked = this.checked;
    });
    updateBatchDeleteButton();
});
</script>
{% endblock %} 